#include "UString.h"
#include "Common.h"
#include "qapplication.h"
#include <QDebug>
#include <QProcess>
using namespace std;

void ustring_usage()
{
    UString str1 = UString("ustring:") + "hello ustring";
    QString str2 = str1 + "\n\t ss";
    std::string str3 = str1;
    const char * str4 = str1;
    UString str5 = UString(str2) + ","+ str3 + "," + str4;


    str1 = str2;
    str1 = str3;
    str1 = str4;
    str1 = str5;

    qout << str1;
    qout << str2;
    qout << str4;
    qout << str5;
    qout << "？？" << (str1 != str2);
    qout << (str1.toStdString() != str3);
    qout << (str1 != str4);
    qout << (str1 != str5);

    UString str("hello WORD\n\tsgsg");

    qout << str;
}

std::tuple<int,QString> exec_cmd(const QString& cmd)
{
    QString Result;
    QProcess exec;
    exec.setProgram("/bin/bash");
    exec.setArguments({"-c",cmd});
    exec.start();
    exec.waitForFinished();
    if(exec.exitCode() < 0)
    {
        Result = exec.readAllStandardError();
        return std::make_tuple(-1,Result);
    }
    Result = exec.readAllStandardOutput();
    return std::make_tuple(0,Result);
}

inline qint64 getpid()
{
    return QCoreApplication::applicationPid();
}

void single_process(char **argv)
{
    UString name = strrchr(argv[0],'/')+1;
    UString cmd = UString("pgrep -a %1 | wc -l").arg(name);
    int Err;QString Res;
    std::tie(Err,Res) = exec_cmd(cmd);
    if( Res.toInt() > 1)
    {
        std::tie(Err,Res) = exec_cmd(QString("pgrep -a %1").arg(name));
        qInfo().noquote() << "current pid:" << getpid();
        qCritical().noquote() << Res;
        std::exit(0);
    }
    qout.noquote() << Res;
}

#define pr(S) #S

int main(int argc,char *argv[])
{
    single_process(argv);
    int *p = nullptr;
    AssertReturnVal( p == nullptr,-1);
}
